<?php

namespace GettextExtractor;

use Nette\ITranslator;

class Translator implements ITranslator
{
    public $countRegexp = '#\%([0-9]+\$)*d#';
    public $paramsRegexp = '#\%([0-9]+\$)*[fs]#';
    public static $codeset = "utf8";
    public static $supported_languages = array(
        "cs" => "čeština",
        "en" => "english",
        "sk" => "slovenčina"
    );
    public static $unix_locales = array (
        "cs" => "cs_CZ",
        "en" => "en_US",
        "sk" => "sk_SK"
    );

    /**
     * Gets the Gettext ready
     *
     * @param string $locale
     * @param string $directory
     * @param string $domain
     */
    public function __construct($language, $directory, $domain = 'messages')
    {
        $locale = self::$unix_locales[$language].".".self::$codeset;
        putenv("LANG=$locale");
        putenv("LANGUAGE=$locale");
        setlocale(LC_ALL, $locale);
        bindtextdomain($domain, $directory);
        textdomain($domain);
        bind_textdomain_codeset($domain, self::$codeset);
    }

    /**
     * Translates the given string.
     * @param  string   message
     * @param  int      count
     * @return string
     */
    public function translate($message, $count = NULL)
    {
        $pars = func_get_args();

        if (!preg_match($this->countRegexp, $message)) {
            $message = gettext($message);
        } else {
            $split = preg_split($this->countRegexp, $message);
            $n = preg_match($this->paramsRegexp, $split[0]);

            if (!isset($pars[$n+1]))
                throw new InvalidArgumentException('Insufficient number of arguments in translate function');

            $message = ngettext($message, $message, $pars[$n+1]);
        }

        if (count($pars)>1) {
            array_shift($pars);
            return vsprintf($message, $pars); // parametrizovane preklady zatim nefunguji
        }

        return $message;
    }
}